<?php
namespace Home\Controller;
use Common\Util\ThinkSDK\ThinkOauth;
/**
 * 游客访问
 * @author liubo <liubo@ilongyuan.com.cn>
 */
class VisitorController extends HomeController {

    public function _initialize() {
        parent::_initialize();
        C('DEFAULT_THEME', 'ui3');
    }

    public function index() {
        if (IS_MOBILE) {
            $this->redirect(U('Download/index'));
            return;
        }
        // if (UID > 0) {
        //     $this->redirect(U('Home/Ucenter/index'));
        // }
        $map = ['web_visible' => 1];
        if(UID) {
            $this->user = event('User')->detail(UID);
        } else {
            $map['visitor_visible'] = 1;
        }
        $this->topics = array_values(event('Topic')->lists($map, 'id,title'));
        $this->races = $this->_race();

        C('DEFAULT_THEME', 'v4');
        $this->commentPager = 5;
        $this->adCode = 'webhome';

        setRedirect();
        $this->assign('currentTab', 'home');
        $this->assign('title', '主页');
        return $this->display('Visitor/index');
    }

    /**
     * 主页视频列表数据
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    public function videolist()
    {
        $topic_id = I('id', 0, 'intval');
        if (empty($topic_id)) {
            $this->ajaxReturn(array('state'=>-2, 'info'=>'参数错误'));
        }

        $p = I('p', 1, 'intval');
        $timestamp = I('timestamp', 0, 'intval');
        $limit = I('limit', 10, 'intval');

        // $limit最大值20
        $limit > 20 && $limit = 20;

        $vEvent = event('Video');
        $games = !UID ? [] : event('GameScribe')->mine(UID);
        $total = 0;
        switch ($topic_id) {
            case 4:
                // 逛一逛
                !empty($games) && $map['game_id'] = ['in', $games];
                $vids = $vEvent->randomLists($map, $limit);
                break;
            case 5:
                // 我的关注
                $vids = $this->_follow($games, $timestamp, $limit, $total);
                break;
            case 6:
                // 热门视频
                $vids = event('VideoHot')->getData($games, $p, $limit, $total);
                break;
            case 7:
                // 手机专区
                $map = ['game_id' => 9];
                $vids = event('Video')->getVideos($map, $p, $limit);
                $total = event('Video')->total($map);
                break;
            default:
                $vids = $vEvent->getByTopicAndGame($topic_id, $games, $timestamp, $limit, $total);
                break;
        }

        $videos = $this->lists_format($vids);
        $data = [
            'videos' => $videos,
            'total' => $total,
        ];
        $this->ajaxReturn(array('state'=>0, 'info'=>'', 'data' => $data));
    }

    /**
     * 我的关注数据
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    private function _follow($games = [], $timestamp = 0, $limit = 10, &$total) {
        $vService = service('Video');

        if (UID) {
            $fEvent = event('Follow');
            $follow_uids = $fEvent->mine($uid);
        }
        $query[] = array(
            'recommend' => $vService::RECOMMEND_YES,
        );
        !empty($follow_uids) && $query[]['uid'] = array('$in' => $follow_uids);
        !empty($games) && $query[]['game_id'] = array('$in' => $games);
        $map['$and'][]['$or'] = $query;
        $map['$and'][]['status'] = $vService::STATUS_PASS;
        $map['$and'][]['race_id'] = array('$eq' => null); ////非比赛视频
        $map['$and'][]['type'] = $vService::TYPE_NORMAL;
        $total = $vService->where(['_array' => $map])->count();

        $map['$and'][]['create_time'] = $timestamp ? array('$lt' => $timestamp) : array('$gt' => 0);
        $where['_array'] = $map;
        $res = $vService->where($where)->order('create_time desc')->limit($limit)->field('id')->select();
        $vids = [];
        foreach ($res as $value) {
            $vids[] = $value['id'];
        }
        return $vids;
    }

    private function _race()
    {
        $rgEvent = event('RaceGroup');
        $curDate = date('Y-m-d H:i', time());
        $map = [
            'state' => 1,
            'race_time' => ['lt', $curDate]
        ];
        $games = !UID ? [] : event('GameScribe')->mine(UID);
        if (!empty($games)) {
            $map['game_id'] = ['$in' => $games];
        }
        $ids = $rgEvent->lists($map, 'id', 2, 0, 'race_time desc');

        if(empty($ids)) return [];
        $fieldMap = ['id', 'title', 'subtitle', 'race_date', 'race_hour', 'score', 'team', 'game', 'match', 'cover'];
        $rgEvent = event('RaceGroup');
        $vEvent = event('Video');
        $list = [];
        foreach ($ids as $key => $value) {
            $detail = $rgEvent->info($value['id']);
            $detail['score'] = $detail['score']?array_map('intval', explode('-', $detail['score'])):[];
            $detail['game'] = $this->field_filter($detail['game'], ['id','name','logo']);
            $detail['match'] = $this->field_filter($detail['match'], ['id','title','cover', 'pc_cover']);
            $races = $vEvent->lists(['group_id' => $detail['id'], 'type' => 1], 0, true);
            if (!empty($races) && is_array($races)) {
                sort($races);
                $races = array_slice($races, 0, 4);
            }
            $detail = $this->field_filter($detail, $fieldMap);
            $detail['races'] = $races;
            $list[] = $detail;
        }

        foreach ($list as $k => &$v) {
            uri_format($v['cover']);
            uri_format($v['match']['cover']);
            uri_format($v['match']['pc_cover']);
            if (empty($v['match']['pc_cover'])) {
                $v['match']['pc_cover'] = $v['match']['cover'];
            }
        }
        return $list;
    }


    private function _getTrade($timestamp = 0, $pager = 10) {
        $topicId = 3;// 编辑选推
        $videos = event('Video')->getByTopicAndGame($topicId, [], $timestamp, $pager);

        $filterMap = array('id','title','thumb','pre_uri','uri', 'dpi_levels', 'detail','user','statis','action','create_time','game_id','game','type','icons', 'tags', 'type', 'status', 'dpi_height', 'dpi_width');
        $videos = $this->lists_format($videos, $filterMap);
        // joe add
        if($videos){
            $comEvent  = A('Api/Comments', 'Event');
            $count = count($videos);
            $this->timestamp = $videos[$count-1]['timestamp'];

            $comments = array();
            foreach ($videos as $key => &$video) {
                $video['comments'] = $comEvent->get($video['id'], $this->commentPager, '', array(), true);
                $video['comments_show_count'] = count($video['comments']);
            }
        }
        // joe end
        return $videos;
    }

    /**
     * 推荐视频数据
     * 取每日精选数据
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    public function dailyRecommend($page = 1, $per = 3)
    {
        $res = event('Video')->getDailyRecommentVids($page, $per);
        $recommend = [];
        foreach ($res as $value) {
            $recommend[] = $value['video_id'];
        }
        $filterMap = array(
            'id', 'title', 'thumb', 'pre_uri', 'uri', 'detail',
            'user', 'statis', 'action', 'create_time'
        );
        $recommend = $this->lists_format( $recommend, $filterMap, false );

        if ( IS_AJAX ) {
            if ( empty( $recommend ) ) {
                $this->ajaxReturn( array( 'state'=>-2, 'info'=>'没有更多内容了' ) );
            }else {
                $this->ajaxReturn(array('state' => 0, 'info' => '操作成功', 'data' => $recommend));
            }
        }else {
            return $recommend;
        }
    }

    public function pcSsoLogin() {
        $redirect_url = U('/', [], false, true);
        $state = 'platform:5';

        $sns = ThinkOauth::getInstance('sina');
        $sso_code_uri['sina'] = $sns->code($redirect_url, $state);
        $sns = ThinkOauth::getInstance('qq');
        $sso_code_uri['qq'] = $sns->code('', $state);
        $sns = ThinkOauth::getInstance('weixin');
        $sso_code_uri['weixin'] = $sns->code($redirect_url, $state);
        $this->assign('sso_code_uri', $sso_code_uri);
        C('DEFAULT_THEME', 'ui2');
        $this->display();
    }

    /**
     * 重置密码验证身份
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    public function resetPwdVerify() {
        $data = I('');

        empty($data['mobile']) && $this->ajaxReturn(['state' => -1, 'info' => '手机号不能为空']);
        empty($data['verify']) && $this->ajaxReturn(['state' => -1, 'info' => '验证码不能为空']);

        $userEvent = event('user');
        $checkRes = $userEvent->checkSmsVerify($data['verify'], $data['mobile'], $msg);

        if ($checkRes === false) {
            $this->ajaxReturn(['state' => -1, 'info' => $msg]);
        }

        $user = $userEvent->getUid(['username' => $data['mobile']]);
        if (!$user && !isset($user[0])) {
            $this->ajaxReturn(['state' => -1, 'info' => '用户不存在']);
        }
        session('_resetPwd_Uid', $user[0]);
        $this->ajaxReturn(['state' =>0, 'info' => '验证通过']);
    }

    /**
     * 重置密码
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    public function resetPwd() {
        if (IS_POST) {
            $uid = session('_resetPwd_Uid');
            $password = I('password');

            !$uid && $this->ajaxReturn(['state' => -1, 'info' => '用户信息有误']);
            !$password && $this->ajaxReturn(['state' => -1, 'info' => '密码不能为空']);

            $userEvent = event('user');
            $res = $userEvent->setPwd($uid, $password);
            if ($res === true) {
                $this->ajaxReturn(['state' =>0, 'info' => '重置密码成功']);
            }

            $this->ajaxReturn(['state' => -1, 'info' => $res]);
        } else {
            $this->display();
        }
    }

    public function pcRedirect() {
        $redirect_url = I('redirect', '', 'trim');
        if (UID) {
            redirect($redirect_url);
        }
    }

    public function check_cookies()
    {
        echo '<script type=text/javascript>
                  function cookieEnabled() {
                      document.cookie="cookie_check=check";
                      return document.cookie?true:false;
                  }
              </script>';
    }
}
